const bcrypt=require("bcrypt");
const fs=require("fs");
const path=require("path");
const jwt=require("jsonwebtoken");

exports.hash=(myPlaintextPassword)=>{
    return new Promise((resolve,reject)=>{
        bcrypt.hash(myPlaintextPassword, 10, (err, hash) =>{
            if(err){
                reject(err);
            }else{
                resolve(hash);
            };
        });
    });
};
exports.compare=(myPlaintextPassword,hash)=>{
    return new Promise((resolve,reject)=>{
        bcrypt.compare(myPlaintextPassword,hash,(err,result)=>{
            if(err){
                reject(err);
            }else{
                resolve(result);
            };
        });
    });
};
exports.token=(username)=>{
    let privateKey=fs.readFileSync(path.join(__dirname,"../keys/rsa_private_key.pem"));
    return jwt.sign({username},privateKey,{algorithm:"RS256"});
};
exports.verify=(token)=>{
    let publicKey=fs.readFileSync(path.join(__dirname,"../keys/rsa_public_key.pem"));
    return jwt.verify(token,publicKey);
};